package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.aliyun.GreenTextScan;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.model.media.vo.WmNewsVo;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private AdChannelMapper adChannelMapper;
    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private AdSensitiveMapper adSensitiveMapper;

    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        //参数校验
        if (id==null){
            log.info("审核文章id为空");
            return;
        }
        //查询文章
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews==null){
            log.info("审核的文章不存在return;");
            return;
        }
        //文章状态为4直接保存数据
        if (wmNews.getStatus()==4){
            saveAppArticle(wmNews);
            return;
        }
        //文章状态为8  发布时间<=当前时间 直接保存数据
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存数据
            saveAppArticle(wmNews);
            return;
        }
        if (wmNews.getStatus()==1){
            Map<String,Object> resultMap=handleTextAndImages(wmNews);
            //文本审核
            boolean textScanBoolean=handleTextScan((String)resultMap.get("content"),wmNews);
            if (!textScanBoolean)return;
            //图片审核
            boolean imagesScanBoolean = handleImagesScan((List<String>) resultMap.get("images"), wmNews);
            if (!imagesScanBoolean)return;
            //敏感词审核
            boolean sensitiveScanBoolean = handleSensitive((String) resultMap.get("content"), wmNews);
            if (!sensitiveScanBoolean) return;
            //发布时间大于当前时间
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                //修改文章状态为8
                updateWmNews(wmNews, (short) 8, "审核通过，待发布");
                return;
            }
            //审核通过，修改自媒体文章状态为9  保存app端相关文章信息
            saveAppArticle(wmNews);

        }
    }


    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag=true;
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap.size()>0){
            log.error("文章中包含敏感词");
            //找到了敏感词，审核不通过
            updateWmNews(wmNews, (short) 2, "文章中包含了敏感词");
            flag = false;
        }
        return flag;
    }

    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images==null){
            return true;
        }
        boolean flag=true;
        ArrayList<byte[]> imageList = new ArrayList<>();
        try {
            for (String image : images) {
                String imageName = image.replace(fileServerUrl, "");
                int index = imageName.indexOf("/");
                String groupName = imageName.substring(0, index);
                String imagePath = imageName.substring(index + 1);
                byte[] imageByte = fastDFSClientUtil.download(groupName, imagePath);
                imageList.add(imageByte);
            }
            Map map = greenImageScan.imageScan(imageList);
            if (!map.get("suggestion").equals("pass")){
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                    flag = false;
                }

                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                    flag = false;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return flag;
        }
        return flag;
    }

    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag=true;
        try {
            Map map = greenTextScan.greeTextScan(content);
            if (!map.get("suggestion").equals("pass")){
                if (map.get("suggestion").equals("block")){
                    //修改文章状态 审核失败原因
                    updateWmNews(wmNews,(short) 2,"文章中包含敏感词");
                    flag=false;
                }
                if (map.get("suggestion").equals("review")){
                    updateWmNews(wmNews,(short)3,"文章中包含不确定词汇");
                    flag=false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag=false;
        }
        return flag;
    }

    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //获取文章内容
        String content = wmNews.getContent();
        //存储文本
        StringBuilder sb = new StringBuilder();
        //存储图片
        ArrayList<String> images = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(content, Map.class);
        for (Map map : mapList) {
            if (map.get("type").equals("text")){
                sb.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }
        }
        if (wmNews.getImages()!=null && wmNews.getType()!=0){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content",sb.toString());
        resultMap.put("images",images);

        return resultMap;
    }

    private void saveAppArticle(WmNews wmNews) {
        //保存文章
        ApArticle apArticle=saveArticle(wmNews);
//        wmNews.setArticleId(apArticle.getId());
        //保存文章配置
        saveArticleConfig(apArticle);
        //保存文章内容
        saveArticleContent(apArticle,wmNews);

        updateWmNews(wmNews,(short)9,"审核通过");

    }

    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        //修改
        wemediaFeign.updateWmNews(wmNews);
    }

    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        //保存
        articleFeign.saveArticleContent(apArticleContent);
    }

    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        //保存
        articleFeign.saveArticleConfig(apArticleConfig);
    }

    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLabels(wmNews.getLabels());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(wmNews.getPublishTime());

        //获取作者信息
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById((long)userId);
        if (wmUser!=null){
            String userName = wmUser.getName();
            ApAuthor apAuthor = articleFeign.selectAuthorByName(userName);
            if (apAuthor!=null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        //获取频道信息
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if (adChannel!=null){
            apArticle.setChannelId(adChannel.getId());
            apArticle.setChannelName(adChannel.getName());
        }

        return articleFeign.saveArticle(apArticle);
    }

    @Override
    public ResponseResult findNews(NewsAuthDto dto) {
        ResponseResult responseResult = wemediaFeign.findList(dto);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);

        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //参数校验
        if (dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.审核没有通过
        if(type.equals(0)){
            updateWmNews(wmNews,(short)2,dto.getMsg());
        }else if(type.equals(1)){
            //4.人工审核通过
            updateWmNews(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
